/**
 * @description 地图编辑器
 * @author mirahs
 * @email 2892727493@qq.com
 */
import AppConstants from "../../framework/scripts/AppConstants"
import PanelBase from "../../framework/scripts/view/PanelBase"
import Tip from "../core/Tip"
import HtmlUtil from "../util/HtmlUtil"


export default class PanelMapNew extends PanelBase {
    public bundleName: string = 'null'
    public skinPath: string = '_panels/PanelMapNew'
    public panelMaskStyle: number = AppConstants.panelMaskStyle.NoThrough | AppConstants.panelMaskStyle.Black

    private fileMapInput: HTMLInputElement
    private fileMap: File

    private lblMapFile: cc.Label


    protected onInitDone(): void {
        this.fileMapInput = HtmlUtil.getInputFile('mapEditor-file_map_new', 'image/jpeg,image/jpg,image/png')
        this.fileMapInput.onchange = () => {
            const files = this.fileMapInput.files
            if (!files || files.length <= 0) return

            this.fileMap = files[0]
            this.lblMapFile.string = this.fileMap.name
        }

        this.lblMapFile = this.skin.getChildByName('spriteMapFile').getChildByName('lblMapFile').getComponent(cc.Label)
    }

    protected onButtonClick(button: cc.Node): void {
        if (button.name == 'BtnOpenFile') {
            this.fileMapInput.click()
        } else if (button.name == 'BtnCancel') {
            this.close()
        } else if (button.name == 'BtnConfirm') {
            this.onClickBtnConfirm()
        }
    }

    protected onDestroy(): void {
        this.fileMapInput.onchange = null
        this.fileMapInput.value = ''
    }


    private onClickBtnConfirm() {
        if (!this.fileMap) {
            Tip.show('请选择地图文件')
            return
        }

        const editGridWidth = this.skin.getChildByName('editGridWidth').getComponent(cc.EditBox)
        const editGridHeight = this.skin.getChildByName('editGridHeight').getComponent(cc.EditBox)

        const gridWidth = editGridWidth.string ? Number(editGridWidth.string) : 40
        const gridHeight = editGridHeight.string ? Number(editGridHeight.string) : 40
        if (gridWidth < 30 || gridWidth > 100) {
            Tip.show('网格宽度 [30, 100]')
            return
        }
        if (gridHeight < 30 || gridHeight > 100) {
            Tip.show('网格高度 [30, 100]')
            return
        }

        const reader = new FileReader()
        reader.onload = () => {
            const image = new Image()
            image.src = reader.result as string
            image.onload = () => {
                const texture2D = new cc.Texture2D()
                texture2D.initWithElement(image)

                this._args[0](this.fileMap.name, texture2D, gridWidth, gridHeight)

                this.close()
            }
        }
        reader.readAsDataURL(this.fileMap)
    }
}
